import { Injectable, Inject } from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import { Repository } from 'typeorm';
import {
  Controller,
  Get,
  Req,
  Res,
  Post,
  HttpCode,
  Header,
  Param,
  Query,
  UseGuards,
} from '@nestjs/common';

import utils from '../utils';

const moment = require('moment');

import { isEmail, isPhone, phoneCode, isDebug, emailCode } from '../config';

import { User } from '../entities/user.entity';
import { Code } from '../entities/code.entity';

/**
 * 存在code 验证是否过期
 * 没过期 发送
 * 过期 删除 创建 发送
 *
 *
 * 如果不存在用户 则 创建用户
 * 如果存在用户 则 查找 code
 * 如果存在code，则 判断是否过期 ,否则 创建 code 发送
 *
 * 没过期 发送
 * 过期 删除 创建新code 发送
 *
 *
 */

@Controller('code')
export class CodeController {
  constructor(
    @InjectRepository(Code)
    private readonly codeRepository: Repository<Code>,
    @InjectRepository(User)
    private readonly userRepository: Repository<User>,
  ) {}
  @Post('send')
  async send(@Req() req, @Res() res) {
    const { email, type } = req.body;

    const rdCode = utils.getCode();
    const createTime = moment().unix();
    const expireTime = moment()
      .add(emailCode.time, 's')
      .unix();

    await this.codeRepository.delete({ username: email });
    const code = new Code();
    code.username = email;
    code.createTime = createTime;
    code.expireTime = expireTime;
    code.code = rdCode;
    await this.codeRepository.save(code);
    await utils.sendEmail(email, '发芽户外验证码', `您的验证码为${code}`);
    res.json({
      code: 200,
      data: code,
      msg: 'success',
    });
  }
}
